package project.Components;

import com.alibaba.fastjson2.JSON;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import project.Config.HttpSessionConfig;
import project.Controller.UserController;
import project.Service.Impl.DeepSeekService;
import project.Util.MessageUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint(value = "/chat/{id}", configurator = HttpSessionConfig.class)
@CrossOrigin
public class WebSocketServer {
    String username;

    DeepSeekService deepSeekService = new DeepSeekService();
    //创建日志属性
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();

    //存放当前在线连接的用户信息(session池)
    private static final ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();

    //建立websocket连接时调用
    @OnOpen
    public void onOpen(Session session, EndpointConfig config, @PathParam("id") final String id) throws IOException {
        //获取当前HttpSession，用于获取用户名以及通信用的会话
//        username = UserController.username;
        username = id;
        //将会话添加到会话池
        System.out.println(username);
        sessionPool.put(username, session);
        logger.info("有新链接加入，当前总人数为:" + sessionPool.size());
        //获取所有在线用户名
        ArrayList<String> allUserName = getAllUserName();
        //获取消息json转String，格式{system：true,to:null,message:['张三','李四','王五']}
        String message = MessageUtil.getMessage(true, null, allUserName);
        broadcast(message);
    }


    //向所有用户广播message,message为json
    public void broadcast(String message) throws IOException {

        //向所有会话广播当前用户上线
        Set<Map.Entry<String, Session>> entrySet = sessionPool.entrySet();
        //遍历session池
        for (Map.Entry<String, Session> i : entrySet) {
            //发送信息
            if (!Objects.equals(i.getKey(), this.username))
                i.getValue().getBasicRemote().sendText(message);
        }
    }

    public ArrayList<String> getAllUserName() {
        ArrayList<String> allUserName = new ArrayList<>();
        for (Map.Entry<String, Session> stringSessionEntry : sessionPool.entrySet()) {
            allUserName.add(stringSessionEntry.getKey());
        }
        return allUserName;
    }

    //收到浏览器发送的消息时自动调用
    @OnMessage
    public void onMessage(String message) throws IOException {

        //将字符串消息转为java类对象，包含to：要发送的对象，message：要发送的字符串消息
//        Message message1 = JSON.parseObject(message, Message.class);
//        System.out.println(message1.toString());
        //从线程池中获取要发送的对象session并发送消息
//        Session session = sessionPool.get(message1.getTo());
//        session.getBasicRemote().sendText(MessageUtil.getMessage(false, message1.getTo(), message1.getMessage()));
        broadcast(message);
    }


    @OnClose
    public void onClose(Session session) throws IOException {

        sessionPool.remove(username);
        //获取所有在线用户名
        ArrayList<String> allUserName = getAllUserName();
        //获取消息json转String，格式{system：true,to:null,message:['张三','李四','王五']}
        String message = MessageUtil.getMessage(true, null, allUserName);
        //广播
        broadcast(message);
    }
}
